//
//  QCComposeView.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/8.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit
import pop

class QCComposeView: UIView {
    //用来保存创建的6个按钮
    var composeButtonArray:[QCComposeButton] = [QCComposeButton]()

    var targrt:UIViewController?
    
    //给外界提供一个方法用来显示该界面
    func show(target:UIViewController?){
        
     self.targrt = target
       
      target?.view.addSubview(self)
      setupComposeButtonAnim(isUp: true)
    }
    
    //设置 6个按钮的动画
    func setupComposeButtonAnim(isUp:Bool){
        
        var H:CGFloat = 350
        
        //按钮消失时  数组取反
        if !isUp {
            composeButtonArray.reverse()
            H = -350
        }
        
        for (i,button) in composeButtonArray.enumerated() {
            
            //实例化阻尼动画对象
            let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
            //设置终点位置
            anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y - H)
            
            //开始时间
            anSpring.beginTime = CACurrentMediaTime()+Double(i)*0.025
            //弹力
            anSpring.springBounciness = 4
            //速度
            anSpring.springSpeed = 12
            //添加动画
            button.pop_add(anSpring, forKey: nil)
        }
        
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置视图
    private func setupUI(){
        
       self.frame.size = CGSize(width:KSCREENW, height: KSCREENH)
       
       self.backgroundColor = randomColor()
       addSubview(bgImageView)
       addSubview(logoImageView)
        
       bgImageView.snp.makeConstraints { (make) in
        make.edges.equalToSuperview()
        }
       logoImageView.snp.makeConstraints { (make) in
        make.centerX.equalToSuperview()
        make.top.equalToSuperview().offset(100)
        }
        addChildButtons()
    }
    
    private func addChildButtons(){
        //获取到模型数组
    let composeModelArray = loadPlist()
        
        //获取按钮的宽和高
        let buttonW :CGFloat = 80
        let buttonH :CGFloat = 110
        
        //计算间距
        let buttonMargin = (KSCREENW - buttonW*3)/4
        
        //遍历数组
        for (i,composeModel) in composeModelArray.enumerated() {
            //实例化button
            let button = QCComposeButton()
            //设置model
            button.composeModel = composeModel
            
            //添加点击事件
            button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
            //设置size
            button.frame.size = CGSize(width: buttonW, height: buttonH)
            
            //计算索引
            let colIndex = CGFloat(i%3)
            let rowIndex = CGFloat(i/3)
            
            //设置x,y 轴
            button.frame.origin.x = buttonMargin + colIndex*(buttonW + buttonMargin)
            button.frame.origin.y = KSCREENH + rowIndex*(buttonH + buttonMargin)
            
            //设置image 
            button.setImage(UIImage(named:composeModel.icon ?? ""), for: UIControlState.normal)
            
            button.setTitle(composeModel.title, for: UIControlState.normal)
            addSubview(button)
            //添加进可变数组
            composeButtonArray.append(button)
        }
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        setupComposeButtonAnim(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3) {
            self.removeFromSuperview()
        }
    }
    
    //懒加载
    private lazy var bgImageView: UIImageView = {
        
        let  imageView = UIImageView()
        imageView.image = UIImage.screenShot()!.applyLightEffect()
        return imageView
    }()
    
    private lazy var logoImageView: UIImageView = UIImageView(imageName: "compose_slogan")
    
}

extension QCComposeView {
    func buttonClick(btn: QCComposeButton) {
       //设置按钮的放大 缩小
       UIView.animate(withDuration: 0.25, animations: {
        //遍历6个按钮的数组
        for button in self.composeButtonArray {
            button.alpha = 0.2
            
            if btn == button {
                button.transform = CGAffineTransform(scaleX: 2, y: 2)
            }else {
                button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
            }
            
        }
        
       }) { (_) in
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.composeButtonArray {
                button.alpha = 1
                button.transform = CGAffineTransform.identity
            }
            
        }, completion: { (_) in
            /*
             - 命名空间 指得的就是项目的名称
             - 在OC中没有命名空间 也就是说所有的类可以通过字符串转class
             - 在Swift 中 系统提供的类可以通过字符串转class
             - 但是程序员自定义的类需要使用命名空间.自定义类名 才可以完成字符串转class
             */
            // 通过模型中的classname 得到对应的class
            let c = NSClassFromString(btn.composeModel?.classname ?? "")! as! UIViewController.Type
            //实例化一个控制器对象
            let vc = c.init()
            let  composeNav = QCNavViewController(rootViewController: vc)
            self.targrt?.present(composeNav, animated: true, completion: { 
                self.removeFromSuperview()
            })
            
        })
        
        }
        
    }
}
//加载Plist
extension QCComposeView {
    
    func loadPlist() -> [QCComposeModel] {
     let filePath = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        let plistArray = NSArray(contentsOfFile: filePath)!
        
        let tempArray = NSArray.yy_modelArray(with: QCComposeModel.self, json: plistArray) as![QCComposeModel]
        return tempArray
        
    }
}
